package com.zmjmall.demo.api.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.zmjmall.demo.api.AddressService;
import com.zmjmall.demo.constant.GlobalConstant;
import com.zmjmall.demo.dao.AddressMapper;
import com.zmjmall.demo.dto.AddressDTO;
import com.zmjmall.demo.model.Address;
import com.zmjmall.demo.model.SysArea;
import com.zmjmall.demo.repository.MyAddressRepository;
import com.zmjmall.demo.repository.SysAreaRepository;
import com.zmjmall.demo.vo.AddressVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zmj
 * @version 2018/7/11
 */
@Service
@Slf4j
public class AddressServiceImpl extends BaseImpl implements AddressService {

    @Autowired
    private MyAddressRepository myAddressRepository;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private SysAreaRepository sysAreaRepository;

    @Override
    public List<AddressVO> findByUserId(String userId) {
        List<Address> addressList = myAddressRepository.findByUserIdEquals(userId);

        List<AddressVO> result = new ArrayList<>();
        if(addressList != null || addressList.size() > 0) {
            for(Address address: addressList) {
                AddressVO addressVO = new AddressVO();
                BeanUtils.copyProperties(address,addressVO);
                addressVO.setAddressInfo(addressNameByCode(address));
                result.add(addressVO);
            }
            return result;
        }
        return null;
    }

    @Override
    @Transactional
    public int save(AddressDTO addressDTO) {
        Address address = new Address();
        String code = addressDTO.getAddressCode();
        SysArea sysArea = sysAreaRepository.findByCode(code);
        if(sysArea != null) {
            address.setReceiverProvince(code.substring(0,2));
            address.setReceiverCity(code.substring(2,4));
            address.setReceiverDistrict(code.substring(4,6));
        }
        BeanUtils.copyProperties(addressDTO,address);
        address.setId(IdWorker.getIdStr());
        address.setIsDefault(GlobalConstant.ADDRESS_DEFAULT);

        return addressMapper.insert(address);
    }
}
